package com.vstudy.zx.controller;

import com.vstudy.zx.entity.Teacher;
import com.vstudy.zx.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {
    @Autowired
    private TeacherService teacherService;


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login.html";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String username, String password, String role, Model model, HttpServletRequest request) {

        HttpSession session = request.getSession();
        String url = (String) session.getAttribute("preUrl");
        session.removeAttribute("preUrl");
        if (url == null) {
            url = "/";
        } else {
            Map<String, String[]> params = (Map<String, String[]>) session.getAttribute("params");
            String s_params = "";
            if (params != null && params.size() > 0) {
                s_params = "?";
                boolean flag = true;
                for (String k :
                        params.keySet()) {
                    if (flag) {
                        s_params += k + "=" + params.get(k);
                        flag = false;
                    } else {
                        s_params += "&" + k + "=" + params.get(k);
                    }
                }
            }
            url += s_params;
        }


        if ("1".equals(role)) {  // student

            return "login.jsp";
        } else {
            Teacher teacher = teacherService.login(username);
            if (teacher != null) {
                if (password.equals(teacher.getTe_password())) {
                    session.setAttribute("teacher", teacher);
                    return "redirect:" + url;
                } else {
                    model.addAttribute("username", username);
                    model.addAttribute("role", role);
                    model.addAttribute("msg", "密码错误");
                    return "login.jsp";
                }
            } else {
                model.addAttribute("username", username);
                model.addAttribute("role", role);
                model.addAttribute("msg", "用户名不存在");
                return "login.jsp";
            }
        }

    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();
        return "login.jsp";
    }
}
